﻿define([
    'Xjs/ui/View',
    'Xjs/core/util',
    'Xjs/core/viewport',
    'Xjs/ui/Content' // Include it in case that a content is passed to a tooltip
],
function (View, util, viewport) {
    'use strict';

    var type = 'tooltip',
    Tooltip = Xjs.getType(type);

    if (Tooltip) { // It has been already loaded
        return Tooltip;
    }

    // A simple tooltip tag
    Tooltip = util.define({
        base: View,
        
        construct: function (conf, parent) {
            Tooltip.base.constructor.call(this, conf, parent); // Call the base constructor
        },
        type: type,
        requiresId: true, // Since we handle event, we need either to provide an id or have it auto-generated
        visible: false, // Initially invisible (not hidden)
        border: true,

        // Attach the events to the parent component
        onRender: function () {

            var me = this;

            Tooltip.base.onRender.call(me);

            this.parent.on('mouseover', function (evt) {

                var xOffset = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft),
                    yOffset = Math.max(document.documentElement.scrollTop, document.body.scrollTop);

                me.move(evt.clientX + xOffset, evt.clientY + yOffset);
                viewport.adjust(me.id); // Make sure it is completely visible inside the viewport
                me.setVisible(true);
            });

            this.parent.on('mouseout', function () {
                me.setVisible(false);
            });
        },

        // Populates all the content of the children components with declared binders from the data
        valueFrom: function (data) {
            if (this.content) {
                this.content.valueFrom(data);
            }
        },

        // Populates the data from all the content of the children components with declared binders
        valueTo: function (data) {
            if (this.content) {
                this.content.valueTo(data);
            }
        }
    });

    Xjs.registerType(Tooltip);

    return Tooltip;
});